package com.freshfresh.activity.selfcenter;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.freshfresh.activity.BaseActivity;
import com.freshfresh.activity.R;
import com.freshfresh.utils.FreshConstants;
import com.freshfresh.utils.ImageLoadOptions;
import com.freshfresh.utils.UrlConstants;
import com.freshfresh.utils.Utils;
import com.freshfresh.view.SelectPicPopupWindow;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

//个人资料

public class UserInfoActivity extends BaseActivity {
	SpannableString msp = null;  
	TextView tv_mm;
	RelativeLayout rel_photo;
	private SelectPicPopupWindow menuWindow;
	private File tempFile = new File(Environment.getExternalStorageDirectory(),getPhotoFileName());
	private File sdcardTempFile;
	private int crop = 300;
	private ImageView iv_head_photo;
	private ProgressDialog progressDialog;
	String last_imageurl="";
	RelativeLayout rel_back;
	LinearLayout ll_personal_uppwd=null;
	TextView tv_title;
	private LinearLayout ll_address_manager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ac_userinfo);
		initView();
		
	}

	public void initView() {
		 progressDialog = new ProgressDialog(this);
		File filess = new File("/mnt/sdcard/freshfresh");
		//判断文件夹是否存在,如果不存在则创建文件夹
		if (!filess.exists()) {
		filess.mkdir();
		}
		sdcardTempFile = new File("/mnt/sdcard/freshfresh", "tmp_pic_"+ SystemClock.currentThreadTimeMillis() + ".jpg");
		tv_mm=(TextView)findViewById(R.id.tv_mm);
		
		ll_address_manager=(LinearLayout)findViewById(R.id.ll_address_manager);
		rel_back=(RelativeLayout)findViewById(R.id.rel_back);
		iv_head_photo=(ImageView)findViewById(R.id.iv_head_photo);
		tv_title=(TextView)findViewById(R.id.tv_title);
		tv_title.setText("我的资料");
		if(getIntent().getExtras()!=null){
			ImageLoader.getInstance().displayImage(getIntent().getExtras().getString("headurl"), iv_head_photo, ImageLoadOptions.getOptions(R.drawable.app_icon));
		}
		
		ll_personal_uppwd=(LinearLayout)findViewById(R.id.ll_personal_uppwd);
		rel_photo=(RelativeLayout)findViewById(R.id.rel_photo);
		msp = new SpannableString(tv_mm.getText().toString()); 
	        msp.setSpan(new AbsoluteSizeSpan(18,true), 0, tv_mm.getText().toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		tv_mm.setText(msp);
		rel_photo.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				 menuWindow = new SelectPicPopupWindow(UserInfoActivity.this,itemsOnClick);
				//设置弹窗位置
		        menuWindow.showAtLocation(UserInfoActivity.this.findViewById(R.id.rel_photo), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0);
				
			}
		});
		
		ll_personal_uppwd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent=new Intent(UserInfoActivity.this,UpdatePasswordActivity.class);
				startActivity(intent);
			}
		});
		
		rel_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(last_imageurl.equals("")){
					finish();
				}else{
					Intent intent=new Intent();
					intent.putExtra("url", last_imageurl);
					setResult(205,intent);
					UserInfoActivity.this.finish();
				}
			}
		});
		
		ll_address_manager.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent intent=new Intent(UserInfoActivity.this,ModifyGenderOldActivity.class);
				startActivity(intent);
			}
		});
	}

	
	 private View.OnClickListener itemsOnClick = new View.OnClickListener(){
	        public void onClick(View v) {
	            menuWindow.dismiss();
	            switch (v.getId()) {
	                case R.id.item_popupwindows_camera:        //点击拍照按钮
	                	// 选择拍照
	    				Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	    				// 指定调用相机拍照后照片的储存路径
	    				cameraintent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(tempFile));
	    				startActivityForResult(cameraintent, 101);
	                    break;
	                case R.id.item_popupwindows_Photo:       //点击从相册中选择按钮
	                	Intent intent = new Intent("android.intent.action.PICK");
	    				intent.setDataAndType(
	    						MediaStore.Images.Media.INTERNAL_CONTENT_URI, "image/*");
	    				intent.putExtra("output", Uri.fromFile(sdcardTempFile));
	    				intent.putExtra("crop", "true");
	    				intent.putExtra("aspectX", 1);// 裁剪框比例
	    				intent.putExtra("aspectY", 1);
	    				intent.putExtra("outputX", crop);// 输出图片大小
	    				intent.putExtra("outputY", crop);
	    				startActivityForResult(intent, 100);
	                	break;
	                case R.id.item_popupwindows_cancel:       //点击
	                    break;
	                default:
	                    break;
	            }
	        }

	    };

	
	 // 使用系统当前日期加以调整作为照片的名称
		private String getPhotoFileName() {
			Date date = new Date(System.currentTimeMillis());
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"'IMG'_yyyyMMdd_HHmmss");
			return dateFormat.format(date) + ".jpg";
		}

		
		
		
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			if (requestCode == 100) {
				Bitmap bmp = BitmapFactory.decodeFile(sdcardTempFile
						.getAbsolutePath());
				Log.e("路径是什么……", sdcardTempFile.getAbsolutePath());
				reg(UserInfoActivity.this, bmp);
				
			} else if (requestCode == 101) {
				// 选择拍照
				startPhotoZoom(Uri.fromFile(tempFile));
			} else if (requestCode == 102) {
				if (data != null)
					// setPicToView(data);
					sentPicToNext(data);

			}
		}

		private void startPhotoZoom(Uri uri) {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, "image/*");
			// crop为true是设置在开启的intent中设置显示的view可以剪裁
			intent.putExtra("crop", "true");

			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);

			// outputX,outputY 是剪裁图片的宽高
			intent.putExtra("outputX", 300);
			intent.putExtra("outputY", 300);
			intent.putExtra("return-data", true);
			intent.putExtra("noFaceDetection", true);
			startActivityForResult(intent, 102);

		}

		// 将进行剪裁后的图片传递到下一个界面上
		private void sentPicToNext(Intent picdata) {
			Bundle bundle = picdata.getExtras();
			if (bundle != null) {
				Bitmap photo = bundle.getParcelable("data");
				if (photo == null) {
				} else {
					reg(UserInfoActivity.this, photo);
				}

				ByteArrayOutputStream baos = null;
				try {
					baos = new ByteArrayOutputStream();
					photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
					byte[] photodata = baos.toByteArray();
					System.out.println(photodata.toString());
					// Intent intent = new Intent();
					// intent.setClass(RegisterActivity.this, ShowActivity.class);
					// intent.putExtra("photo", photodata);
					// startActivity(intent);
					// finish();
				} catch (Exception e) {
					e.getStackTrace();
				} finally {
					if (baos != null) {
						try {
							baos.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		
		
		public static String encodeBase64File(String paramString)
			    throws Exception
			  {
			    File localFile = new File(paramString);
			    FileInputStream localFileInputStream = new FileInputStream(localFile);
			    byte[] arrayOfByte = new byte[(int)localFile.length()];
			    localFileInputStream.read(arrayOfByte);
			    localFileInputStream.close();
			    return Base64.encodeToString(arrayOfByte, 0);
			  }
		
		
		
		
		
		
		public  void reg(final Context cont,Bitmap photodata) {  
	        try {  
	        	progressDialog.setMessage("正在上传文件...");
				progressDialog.show();
	            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
	              
	            //将bitmap一字节流输出 Bitmap.CompressFormat.PNG 压缩格式，100：压缩率，baos：字节流  
	            photodata.compress(Bitmap.CompressFormat.PNG, 100, baos);  
	            baos.close();  
	            byte[] buffer = baos.toByteArray();  
	            System.out.println("图片的大小："+buffer.length);  
	              
	            //将图片的字节流数据加密成base64字符输出  
	            String photo = Base64.encodeToString(buffer, 0, buffer.length,Base64.DEFAULT);  
	  
	            //photo=URLEncoder.encode(photo,"UTF-8");  
	            
	            SharedPreferences userShared = FreshConstants.getUserShared(UserInfoActivity.this);
				String customerid=userShared.getString("userid", "");
				String token=userShared.getString("token", "");
		    	
	            RequestParams params = new RequestParams();  
                params.put("imagebase", photo);  
                params.put("customerid", customerid);
				params.put("token", token);
                String url = "http://www.freshfresh.com/catalog/index/uploadPhoto";  
	   
	              
	                        AsyncHttpClient client = new AsyncHttpClient();  
	                        client.post(url, params, new AsyncHttpResponseHandler() {  
	                        @Override    
	                    public void onSuccess(int statusCode, String content){   
	                			progressDialog.dismiss();
	                			Log.e("上传成功…………", content);
	                			String imageid=Utils.parseJsonStr(content).get("imageid").toString();
	                			String imageurl=Utils.parseJsonStr(content).get("imageurl").toString();
	                			modifyHeaderPhoto(imageid, imageurl);
	                			
	                    Toast.makeText(cont, "头像上传成功!", 0).show();   
	                         }    
	                    @Override    
	                    public void onFailure(Throwable e, String data){   
	                    	progressDialog.dismiss();
	                    	Log.e("上传成功…………", data);
	                    Toast.makeText(cont, "头像上传失败!", 0)  
	                        .show();   
	                }  
	            });  
	   
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	  
	    }  
		
		
		
		protected void modifyHeaderPhoto(String paramString1, final String paramString2){
			progressDialog.setMessage("正在修改...");
			progressDialog.show();
			SharedPreferences userShared = FreshConstants.getUserShared(UserInfoActivity.this);
			String customerid=userShared.getString("userid", "");
			String token=userShared.getString("token", "");
			String str_mobile=userShared.getString("mobile", "");
			
			Map<String, String> params = new HashMap<String, String>();
			params.put("customerid", customerid);
			params.put("token", token);
			
			params.put("mobile", str_mobile);
			params.put("headimageid", paramString1);
			
			executeRequest(new StringRequest(UrlConstants.getUserInfoChange, params,
					new Response.Listener<String>() {

						@Override
						public void onResponse(String arg0) {
							progressDialog.dismiss();
							Log.e("arg0个人信息是多少………………", arg0);
							if (Utils.parseJsonStr(arg0).get("result").toString().equals("1")) {
								Toast.makeText(UserInfoActivity.this, "保存成功", 1).show();
								ImageLoader.getInstance().displayImage(paramString2, iv_head_photo, ImageLoadOptions.getOptions(R.drawable.app_icon));
								last_imageurl=paramString2;
								
								SharedPreferences userShared = FreshConstants
										.getUserShared(UserInfoActivity.this);
								Editor editor = userShared.edit();
								editor.putString("head_url", last_imageurl);
								editor.commit();
								
							} else {
								
							}
						}

					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError arg0) {
							progressDialog.dismiss();
						}
					}));
		  }
		
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			return super.onKeyDown(keyCode, event);
		}
		
		@Override
		public boolean dispatchKeyEvent(KeyEvent event) {
			
			if (event.getAction() != KeyEvent.ACTION_UP&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
				if(last_imageurl.equals("")){
					finish();
				}else{
					Intent intent=new Intent();
					intent.putExtra("url", last_imageurl);
					setResult(205,intent);
					UserInfoActivity.this.finish();
				}
				
			}
			return super.dispatchKeyEvent(event);
		}
		
}